package com.example.mobileeducationstudentv;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class ReadAssignment extends Activity {

	// to hold questions
	public class Question {
		public String question;
		// 0 = multi, 1 = open
		public Integer type;
		public List<String> Answers;
		// 1 = A, 2=B etc..
		public String correct;
		public Integer score;
	}

	// to hold quiz information
	public class Quiz {
		public String Id;
		// public String Name;
		public List<Question> questions;
	}

	// declarations
	public Quiz quiz;
	public int currentQuestion;
	public boolean done;
	public int fullScore;
	public int maxfullScore;
	static Button btnQuit;
	static Button btnNext;
	static TextView lblQuestion, lblResult;
	static RadioGroup rgRadiogroup;
	static EditText editQuestion;
	static RadioButton rb0, rb1, rb2, rb3, rb4;
	static FileDataStorage db;
	static String abspath;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// initialize database
		db = new FileDataStorage(this);
		// initialize layout and buttons
		setContentView(R.layout.readassignment);
		btnQuit = (Button) findViewById(R.id.btnQuit);
		btnNext = (Button) findViewById(R.id.btnNext);
		lblQuestion = (TextView) findViewById(R.id.question);
		lblResult = (TextView) findViewById(R.id.resultLabel);
		rgRadiogroup = (RadioGroup) findViewById(R.id.radioGroup);
		editQuestion = (EditText) findViewById(R.id.openAnswer);
		rb0 = (RadioButton) findViewById(R.id.radio0);
		rb1 = (RadioButton) findViewById(R.id.radio1);
		rb2 = (RadioButton) findViewById(R.id.radio2);
		rb3 = (RadioButton) findViewById(R.id.radio3);
		rb4 = (RadioButton) findViewById(R.id.radio4);

		// quit button that shows a prompt if quiz is uncompleted, otherwise
		// quit to main page
		btnQuit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (!done) {
					new AlertDialog.Builder(v.getContext())
							.setIcon(android.R.drawable.ic_dialog_alert)
							.setTitle("Quit")
							.setMessage(
									"Are you sure you want to quit? Progress will not be saved.")
							.setPositiveButton("No", null)
							.setNegativeButton("Yes",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											finish();
										}

									}).show();
				} else {
					finish();
				}
			}
		});

		// initialize variables and visibilities
		currentQuestion = 0;
		fullScore = 0;
		done = false;
		rgRadiogroup.setVisibility(0);
		lblResult.setVisibility(8);
		btnNext.setText("Next Question");
		Bundle map = getIntent().getExtras().getBundle("quizdata");
		String filename = map.getString("filename");
		abspath = map.getString("abspath");
		btnNext.setVisibility(0);
		mReadJsonData(filename);
		Log.e("File Loaded", filename);
		showQuiz();

		// next button will show next question if possible, otherwise submit
		// assignment
		btnNext.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				checkThisQuestion();
				currentQuestion++;
				if (currentQuestion == (quiz.questions.size() - 1)) {
					btnNext.setText("Submit!");
				}
				if (currentQuestion == (quiz.questions.size())) {
					done = true;
				}
				showQuiz();

			}
		});
	}

	// checks questions with answers from JSON object and keeps score
	private void checkThisQuestion() {
		if (currentQuestion > -1 && quiz.questions.size() > currentQuestion
				&& quiz.questions.get(currentQuestion) != null) {
			Question q = quiz.questions.get(currentQuestion);
			int tmpscore = 0;
			if (q.type == 0) {
				// multi question
				if (q.correct.equals("1") && rb0.isChecked()) {
					tmpscore = 10;
				}
				if (q.correct.equals("2") && rb1.isChecked()) {
					tmpscore = 10;
				}
				if (q.correct.equals("3") && rb2.isChecked()) {
					tmpscore = 10;
				}
				if (q.correct.equals("4") && rb3.isChecked()) {
					tmpscore = 10;
				}
				if (q.correct.equals("5") && rb4.isChecked()) {
					tmpscore = 10;
				}
			} else {
				// open question
				// get answers
				String s = editQuestion.getText().toString().toLowerCase();
				// get correct
				int l = q.Answers.size();
				for (int j = 0; j < l; j++) {
					if (s.contains(q.Answers.get(j).toLowerCase())) {
						tmpscore++;
					}

				}
				// final score for open
				tmpscore = Math.round((tmpscore / (float) l) * 10);
			}
			q.score = tmpscore;
			fullScore += tmpscore;
			Log.e("fullScore", Integer.toString(fullScore));
		} else {
			Log.e("Fatal Error", "Checking question failed");
		}
	}

	// quiz display for each question
	public void showQuiz() {
		// states if done is false, show a question
		// if done is true, show end screen
		if (done) {
			int perc = Math.round((fullScore / (float) maxfullScore) * 100);
			lblResult.setText("You finished the test.\nYou got "
					+ Integer.toString(fullScore) + " points out of "
					+ Integer.toString(maxfullScore) + "\nWhich is "
					+ Integer.toString(perc) + "%");
			lblResult.setVisibility(0);
			rgRadiogroup.setVisibility(8);
			editQuestion.setVisibility(8);
			btnNext.setVisibility(8);
			lblQuestion.setVisibility(8);
			// update db + send text message
			db.takeQuiz(abspath, perc, quiz.Id);
		} else {
			if (currentQuestion < quiz.questions.size()) {
				// show a question
				Question que = quiz.questions.get(currentQuestion);
				lblQuestion.setText(que.question);
				Log.e("View Type", Integer.toString(que.type));
				if (que.type == 0) {
					// multi question
					rgRadiogroup.setVisibility(0);
					rgRadiogroup.clearCheck();
					editQuestion.setVisibility(8);
					int l = que.Answers.size();
					if (l > 0) {
						rb0.setText(que.Answers.get(0));
						rb0.setVisibility(0);
					} else {
						rb0.setVisibility(8);
					}
					if (l > 1) {
						rb1.setText(que.Answers.get(1));
						rb1.setVisibility(0);
					} else {
						rb1.setVisibility(8);
					}
					if (l > 2) {
						rb2.setText(que.Answers.get(2));
						rb2.setVisibility(0);
					} else {
						rb2.setVisibility(8);
					}
					if (l > 3) {
						rb3.setText(que.Answers.get(3));
						rb3.setVisibility(0);
					} else {
						rb3.setVisibility(8);
					}
					if (l > 4) {
						rb4.setText(que.Answers.get(4));
						rb4.setVisibility(0);
					} else {
						rb4.setVisibility(8);
					}
				} else {
					// open question
					rgRadiogroup.setVisibility(8);
					editQuestion.setText("");
					editQuestion.setVisibility(0);
				}
			} else {
				// something went wrong
				Log.e("Error", "Incorrect state - something went wrong");
			}
		}
	}

	// reads JSON file to string
	public void mReadJsonData(String filename) {
		try {
			File f = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ "/MobileEducation/Assignments/"
					+ filename);
			FileInputStream is = new FileInputStream(f);
			int size = is.available();
			byte[] buffer = new byte[size];
			is.read(buffer);
			is.close();
			String data = new String(buffer);
			setQuizFromJson(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// initializing JSON object from json string
	public void setQuizFromJson(String json) {
		try {
			// getting JSON string
			JSONObject jObject = new JSONObject(json);
			quiz = new Quiz();
			// Getting id and questions
			quiz.Id = jObject.getString("id");
			quiz.questions = new ArrayList<Question>();
			JSONArray questionArray = jObject.getJSONArray("questions");

			// looping through All questions
			Log.e("Number of questions:",
					Integer.toString(questionArray.length()));
			for (int i = 0; i < questionArray.length(); i++) {
				Log.e("Question", "This is the start");
				JSONObject jQuestionObject = questionArray.getJSONObject(i);
				Question qo = new Question();

				String s = jQuestionObject.getString("type");
				if (s.equals("multi")) {
					qo.type = 0;
				} else {
					qo.type = 1;
				}
				qo.Answers = new ArrayList<String>();
				if (qo.type == 0) { // multi
					qo.correct = jQuestionObject.getString("cor");
				} else {
					qo.correct = "-1";
				}
				JSONArray AnsArray = jQuestionObject.getJSONArray("ans");
				for (int j = 0; j < AnsArray.length(); j++) {
					qo.Answers.add(AnsArray.getString(j));
				}
				qo.question = jQuestionObject.getString("q");

				quiz.questions.add(qo);
				Log.e("Question", "Added");

			}
			maxfullScore = quiz.questions.size() * 10;
		} catch (JSONException e) {
			Log.e("Parsing error: ", e.getMessage());
		}
	}
}